import { defineStore } from 'pinia';
import { removeRouteListener } from '@/utils/route-listener';
import type { Protocol } from '@/api/types';
import { LoginData, LoginUser, currentUser, login } from '@/api/user-api';
import { Message } from '@arco-design/web-vue'; // 导入选项数据类型
import { setToken } from '@/utils/auth';

const useUserStore = defineStore('user', {
  state: (): LoginUser => ({
    id: undefined,
    userCode: undefined,
    email: undefined,
    abbreviation: undefined,
    fullName: undefined,
    tel: undefined,
    address: undefined,
    avatar: undefined,
    sessionId: undefined,
    expireAt: undefined,
    role: undefined,
  }),

  getters: {
    userInfo(state: LoginUser): LoginUser {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<LoginUser>) {
      setToken(partial.sessionId);
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    info(): LoginUser {
      return this.userInfo;
    },

    // Login
    async login(data: LoginData): Promise<Protocol<LoginUser>> {
      const protocol = await login(data);
      if (protocol.returncode === 0 && protocol.result !== null) {
        this.setInfo(protocol.result);
      }
      return protocol;
    },

    // Login
    async current(): Promise<LoginUser> {
      const protocol = await currentUser();
      if (protocol.returncode === 0) {
        this.setInfo(protocol.result);
        return this.userInfo;
      }
      return null;
    },
    // Callback for logout
    logoutCallBack() {
      this.resetInfo();
      removeRouteListener();
    },
    // Logout
    async logout() {
      this.logoutCallBack();
    },
  },
});

export default useUserStore;
